import { MD } from "../GMDBase/MD";
import { gcfg } from "../../gcfg"; 
import FB from "./FB";

enum ADLoadState {
    none,           //初始空状态
    loading,        //加载中
    load_comlepte,  //加载完成
    showing, //显示中
}

class RewardedVideoAd
{
    constructor(adUnitId:string,isVideo:boolean)
    {
        this.m_adUnitId = adUnitId
        this.m_isVideo = isVideo
    }

    get IsVidio():boolean
    {
        let supportedAPIs: string[] = FBInstant.getSupportedAPIs();
        return this.m_isVideo&&//视频模式
                supportedAPIs.indexOf('getRewardedVideoAsync') !== -1//视频相关的api可用
    }

    public load()
    {   
        if(this.m_ADLoadState!=ADLoadState.none) return

        if(this.m_preloadedRewardedVideo)
        {
            this._load()
        }else
        {
            let supportedAPIs: string[] = FBInstant.getSupportedAPIs();
            this.m_ADLoadState = ADLoadState.loading

            var handel 
            if(this.IsVidio)//视频广告
            {
                cc.log("装载视频广告")
                handel = FBInstant.getRewardedVideoAsync(gcfg.ADUnitId)
            }else //插屏广告
            {
                if( supportedAPIs.indexOf('getInterstitialAdAsync')!== -1 )
                { 
                    cc.log("装载插屏广告")
                    handel = FBInstant.getInterstitialAdAsync(gcfg.InterstitialADId)
                }else
                {
                    cc.log("无法显示广告，api不支持！");

                    wx.showToast({
                        title:"No available Ad right now,try again later."
                    })
                    
                    return
                }
            }
 

            
            

            handel.then((rewarded)=>{
                cc.log('get ad success');
                this.m_preloadedRewardedVideo = rewarded;
                this._load()
            })
            .catch((err)=>{
                this.m_ADLoadState = ADLoadState.none
                cc.error('get ad failed: ' + err.message);
                if(this.m_onErrFunc) this.m_onErrFunc()
            });
       }
    }

    loadDone()
    {
        cc.log('ad loadDone.')

        if(this.m_onLoadFunc) this.m_onLoadFunc()
            

        if(this.m_ADLoadState==ADLoadState.showing)
            this.show()
        else
            this.m_ADLoadState = ADLoadState.load_comlepte
    }

    _load()
    {
        cc.log('ad _load')
        this.m_preloadedRewardedVideo.loadAsync()
        .then(()=> {
            cc.log('ad preloaded')
            this.loadDone()
        })
        .catch((err)=>{
            cc.error('ad failed to preload: ',err.message,err.code);
            //this.m_ADLoadState = ADLoadState.none
            //if(this.m_onErrFunc) this.m_onErrFunc()
            //    err.code=="ADS_NO_FILL"||
            //    err.code=="ADS_FREQUENT_LOAD"

            /*
            if(err.code=="ADS_FREQUENT_LOAD")
            {
                this.loadDone()
            }
            else
            */
            {
                this.m_ADLoadState = ADLoadState.none
                wx.showToast({
                    title:"No available Ad right now,try again later."
                })
            }
            //    this._reload()
        });
    }

    public show()
    {
        /*
        if(
            this.m_ADLoadState != ADLoadState.load_comlepte&&
            this.m_ADLoadState != ADLoadState.showing
        )
        */


        if(!this.m_preloadedRewardedVideo) return

        this.m_ADLoadState = ADLoadState.showing
        this.m_preloadedRewardedVideo.showAsync()
        .then(()=> {
            // Perform post-ad success operation
            cc.log('Rewarded video watched successfully',this.m_preloadedRewardedVideo)

            //code
            //"PENDING_REQUEST"


            this.m_ADLoadState = ADLoadState.none
            this.m_preloadedRewardedVideo = null


            if(this.IsVidio&&this.m_onCloseFunc)
            {
                this.m_onCloseFunc({isEnded:true})
            }
        })
        .catch((e)=> {
            if(e.code=="PENDING_REQUEST")//实际是成功显示的，忽略错误
            {
                this.m_ADLoadState = ADLoadState.none
                cc.error("ad show failed#1 code:",e.code);
            }else if(e.code=="RATE_LIMITED")//请求过于频繁
            {
                cc.error("ad show failed#2 code:",e.code);
                this.m_ADLoadState = ADLoadState.none 

                wx.showToast({
                    title:"No available Ad right now,try again later."
                })
                //if(this.m_onErrFunc) this.m_onErrFunc()
            }
            else
            { 
                cc.error("ad show failed#3 ",e.message,e.code);
                this._reload()
            }
        });
    }

    _reload()
    {
        //定时重试，防止调用堆栈溢出
        setTimeout(() => {
            this._load()    
        },
        1000
        );
        
    }

    //激励视频关闭事件
    public onClose(func:Function)
    {
        this.m_onCloseFunc = func
        //res.isEnded//是否观看完成
    }

    //激励视频装载完成事件
    public onLoad(func:Function)
    {
        this.m_onLoadFunc = func
    }

    //激励视频加载失败
    public onError(func:Function)
    {
        this.m_onErrFunc = func
    }

    m_onCloseFunc:Function
    m_onLoadFunc:Function
    m_onErrFunc:Function
    m_adUnitId:string
    m_preloadedRewardedVideo:any
    m_isVideo:boolean
    m_ADLoadState:ADLoadState = ADLoadState.none
}

class SocketTask
{
    constructor(handel:WebSocket)
    {
        this.m_handel = handel
    }

    public close(obj)
    {
        this.m_handel.close()
    }

    public send(obj)
    {
        this.m_handel.send(obj.data)
    }
    
    public onMessage(func:Function)
    {
        this.m_handel.onmessage = (evt:MessageEvent)=>{
                func(evt)   
        }
    }

    public onOpen(func:Function)
    {
        this.m_handel.onopen = (evt:Event)=>{
            func(evt)   
        }
    }

    public onClose(func:Function)
    {
        this.m_handel.onclose = (evt:CloseEvent)=>{
            func(evt)   
        }
    }

    public onError(func:Function)
    {
        this.m_handel.onerror = (evt:Event)=>{
            func(evt)   
        }
    } 

    m_handel:WebSocket
}

//模拟wx函数
export default class _wx
{
    public static showToast(obj:any)
    {
        cc.log("showToast",obj.title)
        MD.WndPopupTip.ShowTip(obj.title)
    }

    public static clearStorageSync()
    {
        cc.sys.localStorage.clear();
    }

    public static hideLoading(obj:any)
    {
        
    }

    public static showLoading(obj:any)
    {

    }

    public static get IsQWDev():boolean
    {
        var re = FB.InFB?false:true 
        return re
    }

    public static request(obj:any)
    {
        var xhr = cc.loader.getXMLHttpRequest()
        xhr.onreadystatechange = function () {
            if (xhr.readyState != 4) return 

            try{ 
                if(xhr.status >= 200 && xhr.status < 400){
                    var response = xhr.responseText;
                    // console.log(response)
                    if(response){
                        if(obj.success) obj.success({data:response})
                    }else{
                        if(obj.fail) obj.fail() 
                    }
                }else{
                    if(obj.fail) obj.fail() 
                }
            }catch(msg)
            {
                if(obj.fail) obj.fail()
                cc.error(msg)
            } 
        };

        var url = obj.url

        if(obj.method=="POST")
        {
            xhr.open("POST", url, true);
            var postData
            if((typeof obj.data=='string')&&obj.data.constructor==String)
                postData = obj.data
            else if((typeof obj.data=='object')&&obj.data.constructor==Array)
                postData = ""//暂不支持数组
            else
                postData = JSON.stringify(obj.data)

            xhr.send(postData);
        }else
        { 
            
            var p = ""
            //处理参数
            for(var key in obj.data)
            {
                var v = obj.data[key]
                var kv = key+"="+v
                if(p=="") 
                    p = kv
                else
                    p+="&"+kv
            }

            if(p!="") url+="?"+p
            xhr.open("GET", url,true);
            xhr.send();
        }
    }

    public static connectSocket(obj:any):SocketTask
    {
        var handel = new WebSocket(obj.url)
        return new SocketTask(handel)
    }

    public static showModal(obj:any)
    {
        MD.WndMsgBox.ShowOKCancel(
            obj.title, 
            obj.content, 
            obj.confirmText?obj.confirmText:"Ok", 
            obj.cancelText?obj.cancelText:"Cancel", 
            (isok)=>{
                if(isok&&obj.success) 
                {
                    obj.success({confirm:true})
                } 

                if(obj.complete)
                {
                    var res:any = {}
                    if(isok) 
                        res.confirm = true
                    else
                        res.cancel = true

                    obj.complete(res)
                }
 
            }
            ) 
    }

    public static createRewardedVideoAd(obj:any)
    {
        return new RewardedVideoAd(obj.adUnitId,true)
    }

    public static createInterstitialAd(obj:any)
    {
        return new RewardedVideoAd(obj.adUnitId,false)
    }
}

window["wx"] = _wx
 